import { Component, OnInit, ViewEncapsulation } from '@angular/core';

import {UserActivityService} from "@shared/service/user-activity/user-activity.service";
import {ActivatedRoute, Params} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";
import {SNSResult, UserInfoVO} from "@interface/index";


@Component({
  selector: 'seed-third-login',
  templateUrl: './third-login.component.html',
  styleUrls: ['./third-login.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class RedirectionThirdLoginComponent implements OnInit {

  constructor(
    private _auth: AuthService,
    private _route: ActivatedRoute,
    private _userService: UserActivityService
  ) {
    this._route.params.subscribe((params: Params) => {
      if ( params['thirdType'] ) {
        this.doLogin(params['thirdType'], this.urlParams);
      }
    });
  }

  get urlParams() {
    let serchUrl = window.location.href;
    const length = serchUrl.indexOf('?');
    serchUrl = serchUrl.substring(length) + '&chanelId=30';
    // this.url =  serchUrl;
    return serchUrl;
  }

  doLogin(thirdType: string, urlParams: string) {
    if (!thirdType || !urlParams) { return; } ;
    this._userService.ThirdLogin(this.urlParams, thirdType).subscribe(res => {
      if (res.result === '0') {
        this.redirect(res);
      }
    });
  }

  redirect(res: SNSResult<UserInfoVO> ) {
    const redirectUrl = localStorage.getItem('seed_redirectUrl'),
      {userId, token, openId} = res.data;
    this._auth.login(userId, token, '', openId);
    if (redirectUrl) {
      window.location.href = redirectUrl;
    }
  }
  ngOnInit() {
  }

}
